import axios from 'axios'
import store from '@/store'
import storage from 'store'
import message from 'ant-design-vue/es/message'

import {
  VueAxios
} from './axios'
import {
  ACCESS_TOKEN
} from '@/store/mutation-types'


// 创建 axios 实例
const request = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL, // api的base_url
  timeout: 120000 // 请求超时时间
})


// 异常拦截处理器
const errorHandler = error => {
  if (error.response) {
    // 异常响应
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    switch (error.response.status) {
      case 500:
        if (token && data.message === 'Token失效，请重新登录') {
          message.error('很抱歉，登录已过期，请重新登录')
          setTimeout(() => {
            // store.dispatch('Logout').then(() => {
            //   window.location.reload()
            // })
          }, 1000);
        }
        break
      case 504:
        message.error('系统提示-网络超时')
        break
      case 401:
        message.error('未授权，请重新登录')
        if (token) {
          // store.dispatch('Logout').then(() => {
          //   setTimeout(() => {
          //     window.location.reload()
          //   }, 1500)
          // })
        }
        break
      case 403:
        message.error('系统提示-拒绝访问')
        break
      case 404:
        message.error('系统提示-很抱歉，资源未找到')
        break
      default:
        message.error(data.message)
        break
    }
  }
  return Promise.reject(error)
}



// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Authorization'] = "Bearer " + token
  }
  return config
}, errorHandler)


// response interceptor
request.interceptors.response.use((response) => {
  if (response.request.responseType === 'blob') {
    return response
  }
  if (!response.data.success) {
    // message.error(response.data.message);
    return Promise.reject(response.data);
  }
  return response.data.content
}, errorHandler)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}